// pages/my/my.js
const app = getApp();
const url = app.globalData.url;
const WxParse = require('../../wxParse/wxParse.js');  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    logins: false,
    url : app.globalData.url,
    swhzs: false,
    lxkfs: false,
    loding:true,
    userfj:true,
    zqs:true,
    xtsum:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    console.log(o)
    if(o){
      if(o.ck=='kf'){
        this.lxkfs();
      }
    }
  },
  qxxqxqx(){
    this.setData({
      swhzs: false,
      lxkfs: false})
  },
  lxkfs(){
    this.setData({
      lxkfs: true})
  },
  swhzs(){
    this.setData({
      swhzs: true})
  },
  // 定时器
  dinshi: function () {
    this.loding_timer = setTimeout(() => {
      this.peizi();
    }, 10 * 1000)
  },
  // 获取授权订阅消息
  hqdysq(){
    var that=this;
    console.log(that.data.peizi.xcx.dymbid.txt)
    var it=[that.data.peizi.xcx.dymbid.txt];
    console.log(it);
    wx.requestSubscribeMessage({
      tmplIds: it, // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
      success (res) {
       console.log('已授权接收订阅消息')
        wx.navigateTo({
          url: '/pages/xtxx/xtxx'
        })
      },
      fail(r){
        console.log(r)
      }
     })
  },
  // 拨号
  calling: function (e) {
    var tb = e.currentTarget.dataset.tb;
    if (tb == "") {
      wx.showToast({
        title: '电话为空',
        image: '../../img/ico/clear.png',
        duration: 2000
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '要拨打 ' + tb + ' 吗?',
        success: function (res) {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: tb + "",
              success: function () {
                // console.log("拨打电话成功！")
              },
              fail: function () {
                // console.log("拨打电话失败！")
              }
            })
          } else if (res.cancel) {
            // console.log('用户点击取消')
          }
        }
      })
    }
  },
  // 封禁客服
  callkf(){
    var that=this;
    wx.showModal({
      title: '用户被封禁',
      content: '请联系客服,处理用户封禁问题',
      showCancel: true,//是否显示取消按钮
      cancelText: "待会联系",//默认是“取消”
      // cancelColor: '#f',//取消文字的颜色
      confirmText: "联系客服",//默认是“确定”
      // confirmColor: '',//确定文字的颜色
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
          // if (options.finish) {
          // wx.navigateBack({ delta: 1 })
          // }
        } else {
          // wx.makePhoneCall({
          //   phoneNumber: that.data.peizi.xcxkf.dh.txt,
          //   success: function () {
          //     console.log("拨打电话成功！")
          //   },
          //   fail: function () {
          //     console.log("拨打电话失败！")
          //   }
          // })
          that.lxkfs();
        }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  // 弹出登录
  logins(){
    this.setData({ logins: true });
  },
  // 不登录
  bdl(){
    this.setData({logins:false});
  },
  // 跳转url
  tourl(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },
  // 微信登录
  loginWX() {
    var that = this;
    // 发起微信登录请求
    wx.login({
      success: res => {
        console.log(res.code)
        wx.request({
          url: url + 'api/wx/openid.php',
          data: {
            code: res.code
          },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res => {
            that.setData({ openid: res.data.openid });
            that.setData({ 'user.openid': res.data.openid });
            wx.setStorage({
              key: 'openid',
              data: res.data.openid,
            });
            wx.request({
              url: url + 'api/wx/user.php', //仅为示例，并非真实的接口地址
              data: {
                openid: res.data.openid
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                var data = res.data;
                console.log(res)
                if (data.code == 500) {
                  wx.request({
                    url: url + 'api/wx/adduser.php', //仅为示例，并非真实的接口地址
                    data: {
                      userInfo: JSON.stringify(that.data.user),
                    },
                    method: "POST",
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded" // 默认值
                    },
                    success(res) {
                      var data = res.data;
                      if (data.code == 200) {
                        that.setData({ 'user.uid': data.uid });
                        that.hquser();
                      } else {
                        console.log(res)
                        wx.hideLoading();
                        wx.showModal({
                          title: '未知错误',
                          content: '请联系管理员,获取奖励',
                          showCancel: false,//是否显示取消按钮
                          cancelText: "否",//默认是“取消”
                          cancelColor: '#fc7582',//取消文字的颜色
                          confirmText: "拨打电话",//默认是“确定”
                          confirmColor: '#fc7582',//确定文字的颜色
                          success: function (res) {
                            if (res.cancel) {
                              //点击取消,默认隐藏弹框
                              // if (options.finish) {
                              wx.navigateBack({ delta: 1 })
                              // }
                            } else {
                              wx.makePhoneCall({
                                phoneNumber: that.data.peizi.xcxkf.dh.txt,
                                success: function () {
                                  console.log("拨打电话成功！")
                                },
                                fail: function () {
                                  console.log("拨打电话失败！")
                                }
                              })
                            }
                          },
                          fail: function (res) { },//接口调用失败的回调函数
                          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
                        })
                      }
                    }
                  })
                } else if(data.code==200) {
                  app.fetch('api/wx/upuser', 
                   { gxwx: JSON.stringify(that.data.user), uid: data.data[0].uid }, "GET", 
                   (err, data) => {
                      console.log(data)
                  })
                  that.setData({ user: data.data[0]})
                  that.getcsData();
                } else if(data.code == 300){
                  wx.hideLoading();
                  that.setData({ user: "" })
                  that.setData({ userfj: false });
                  that.callkf();
                }
              }
            })
          }
        })
      }
    })
  },
  //获取 用户信息
  getUser: function () {
    // 获取用户信息
    let that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              console.log(res);
              // let tx = res.userInfo.avatarUrl.substring(0, res.userInfo.avatarUrl.length - 3) + '0';
              let user = res.userInfo;
              that.setData({ user: user })
              // that.getIndex();
              that.loginWX()
            }
          })
        } else {
          that.setData({ loding: true });
        }
      }
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e.detail.errMsg)
    this.bdl();
    wx.showLoading({
      title: '登录中...',
      mask:true,
    })
    if (e.detail.errMsg == 'getUserInfo:ok') {

      this.getUser();
      wx.hideLoading();
    } else {
      wx.hideLoading();
      wx.showModal({
        title: '授权失败',
        content: '请重新授权？',
        showCancel: false,//是否显示取消按钮
        confirmText: "好的",//默认是“确定”
        confirmColor: 'skyblue',//确定文字的颜色
        success: function (res) {

        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
      })
    }
  },
  // 获取数据
  getcsData(){
    let that=this;
    let user=that.data.user;
    let sj = {
      uid: that.data.user.uid,
      ck: 1
    }
    app.fetch('api/wx/getaddlist', sj, "POST", (err, data) => {
      console.log(data);
      that.setData({
        "dt.yfb": data.recordCount,
      });
    })
    sj = {
      uid: that.data.user.uid,
      ck: 3
    }
    app.fetch('api/wx/getaddlist', sj, "POST", (err, data) => {
      console.log(data);
      that.setData({
        "dt.wtg": data.recordCount,
      });
    })
    
  },
  // 获取系统消息
  getxtxx(){
    let that = this;
    let user = that.data.user;
    app.fetch('api/wx/getxtxx', { uid: user.uid, gl: user.isqx == 2 || user.isqx == 3 ? 'gl' : '' }, "POST", 
    (err, data) => {
      console.log(data);
      that.dinshi();
      that.setData({ xtsum: data.recordCount - user.xtxx });
    })
  },
  // 导航
  getdaohang() {
    let that = this;
    let pages = getCurrentPages();
    let currPage = null;
    if (pages.length) {
      currPage = "/" +(pages[pages.length - 1]).route;
    }
    let pz = that.data.peizi.xcxdh;
    console.log(currPage)
    app.fetch('api/wx/getdh', { pgs: 5, lx: 1, isxs: 1 }, "GET", (err, data) => {
      console.log(data)
      for (var i = 0; i < data.data.length; i++) {
        data.data[i].img = url + data.data[i].img;
        data.data[i].cimg = url + data.data[i].cimg;
        if (data.data[i].tzurl == currPage){
          that.setData({"daohang.show":true});
          wx.hideHomeButton();
          
        }
      }
      that.setData({
        "daohang.dhlist": data.data,
        "daohang.recordCount": data.recordCount,
        "daohang.ckpage":currPage,
        "daohang.color": pz.color.txt,
        "daohang.ccolor": pz.ccolor.txt,
        "daohang.background": pz.background.txt,
      });
    })
  },
  // 配置文件
  peizi: function () {
    clearTimeout(this.loding_timer);
    let that = this;
    app.fetch('api/wx/getpeizi', {dlx: 'xcxmy'},"GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: data.data.xcxmy.title.txt
        });
        that.setData({ peizi: data.data, loding: false });
        article_content: WxParse.wxParse('article', 'html', data.data.xcxkf.ptjs.txt, that, 0);
        that.hquser();
        that.getdaohang();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取user信息;
  hquser(){
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0] })
            that.getxtxx();
            // that.hqdysq();
            that.getcsData();
          } else if (data.code == 300) {
            that.setData({ userfj: false });
            that.callkf();
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.peizi();
    let that=this;
    wx.getStorage({
      key: 'zqs',
      success(res) {
        that.setData({
          zqs:false
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("关闭定时器")
    clearTimeout(this.loding_timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("卸载关闭定时器")
    clearTimeout(this.loding_timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})